//
//  MovingAnnotationViewController.m
//  loveSport
//
//  Created by mac on 2017/6/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "MovingAnnotationViewController.h"
//日期选择
#import "FDAlertView.h"
#import "QRBCustomDatePickerView.h"
@interface MovingAnnotationViewController ()<MAMapViewDelegate,UITextFieldDelegate>
{
    CLLocationCoordinate2D coords1[1];
    UITextField *_startTime;
    UITextField *_endTime;
    NSInteger _type;
    MAAnimatedAnnotation *_anno;
}
@property (strong, nonatomic) NSMutableArray *dataArr;
///地图
@property (nonatomic, strong) MAMapView *mapView;
///支持动画效果的点标注
@property (nonatomic, strong) MAAnimatedAnnotation* annotation;

@end

@implementation MovingAnnotationViewController
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [QViewUtility setupNavigationBarBackForController:self backSelector:@selector(back)];
    self.title = @"历史轨迹";
    NSString *startTime = @"2018-04-11 00:00:00";
    NSString *stopTime = @"2018-04-11 12:00:00";
  
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.mapView.delegate = self;
    self.mapView.showsCompass= NO;
    [self.view addSubview:self.mapView];
     [self initButton];
    [self requestDataWithStartTime:startTime EndTime:stopTime];
   

}
- (void)requestDataWithStartTime:(NSString *)start EndTime:(NSString *)end{
    
    
    NSString *url = [QParamService urlWithIOTAction:@"map/locusList"];
    NSString *token =  [QParamService getToken];
    NSString *ID = self.ID;
    NSDictionary *params = @{@"token":token,@"id":ID,@"startTime":start,@"stopTime":end};
    [[QHttpManager sharedManager] POST:url parameterMD5jm:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        NSLog(@"%@",basModel.items);
       
        if([basModel.result isEqualToString:@"success"]){
            
            [self.dataArr removeAllObjects];

            [_mapView removeOverlays:_mapView.overlays];
            
            self.dataArr = basModel.items;
            [self initCoordinates];
            if (_anno == nil) {
                 _anno = [[MAAnimatedAnnotation alloc] init];
            }
           
//            _anno.title = @"znb";
            _anno.coordinate = coords1[0];
            self.annotation = _anno;
            [self.mapView setSelectedAnnotations:@[_anno]];
            [self.mapView addAnnotation:self.annotation];
            
        }
    }];
    
}
- (void)initCoordinates {
    
    CLLocationCoordinate2D coords[self.dataArr.count];
    
    for (int i = 0; i < self.dataArr.count; i++) {
        NSDictionary *dict= self.dataArr[i];
        if (i==0) {
            coords1[0].latitude = [dict[@"lat"] doubleValue];
            coords1[0].longitude = [dict[@"lng"] doubleValue];
            _mapView.centerCoordinate = coords1[0];
            [_mapView setZoomLevel:19.0 animated:YES];
        }
        coords[i].latitude = [dict[@"lat"] doubleValue];
        coords[i].longitude = [dict[@"lng"] doubleValue];
    }
    NSLog(@"%ld",sizeof(coords) / sizeof(coords[0]));
    MAPolyline *polyline1 = [MAPolyline polylineWithCoordinates:coords count:sizeof(coords) / sizeof(coords[0])];
    [self.mapView addOverlays:@[polyline1]];
    
    
}

- (void)initButton
{
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(5, kScreenHeight-40, kScreenWidth-10, 30)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    UIButton *button1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(bottomView.frame.size.width/2, 0, bottomView.frame.size.width/2,30);
    button1.backgroundColor = [UIColor clearColor];
    [button1 setTitle:@"播放" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(button1) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:button1];
    button1.layer.borderWidth = 1;
    button1.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    
    UIButton *button2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(0, 0, bottomView.frame.size.width/2,30);
    button2.backgroundColor = [UIColor clearColor];
    [button2 setTitle:@"停止" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(button2) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:button2];
    button2.layer.borderWidth = 1;
    button2.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 74, kScreenWidth-20, 71)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    
    
    _startTime = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, view.frame.size.width-50, 30)];
    _startTime.delegate = self;
    _startTime.tag = 100;
    [_startTime setBackgroundColor:[UIColor clearColor]];
    UILabel *paddingView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    
    paddingView.text = @"开始时间";
    paddingView.font = [UIFont systemFontOfSize:14];
    paddingView.textColor = [UIColor darkGrayColor];
    paddingView.backgroundColor = [UIColor clearColor];
    _startTime.leftView = paddingView;
    _startTime.leftViewMode = UITextFieldViewModeAlways;
    _startTime.placeholder = @"请选择时间";
    _startTime.font = [UIFont systemFontOfSize:14];
    _startTime.textColor = [UIColor darkGrayColor];
    [view addSubview:_startTime];
    
    
    _endTime = [[UITextField alloc]initWithFrame:CGRectMake(10, 36, view.frame.size.width-50, 30)];
    _endTime.delegate = self;
    _endTime.tag = 200;
      [_endTime setBackgroundColor:[UIColor clearColor]];
    UILabel *paddingView1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 35)];
    
    paddingView1.text = @"结束时间";
    paddingView1.font = [UIFont systemFontOfSize:14];
    paddingView1.textColor = [UIColor darkGrayColor];
    paddingView1.backgroundColor = [UIColor clearColor];
    _endTime.leftView = paddingView1;
    _endTime.leftViewMode = UITextFieldViewModeAlways;
    _endTime.placeholder = @"请选择时间";
    _endTime.font = [UIFont systemFontOfSize:14];
    _endTime.textColor = [UIColor darkGrayColor];
    [view addSubview:_endTime];
    
    UIView *lineView  = [[UIView alloc]initWithFrame:CGRectMake(0, 35, view.frame.size.width, 1)];
   
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [view addSubview:lineView];
    
}

- (void)button3
{
    if (_startTime.text&&_endTime.text) {
        
        [self requestDataWithStartTime:_startTime.text EndTime:_endTime.text];
    }
    
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    FDAlertView *alert = [[FDAlertView alloc] init];
    QRBCustomDatePickerView * contentView=[[QRBCustomDatePickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
    contentView.delegate=self;
    alert.contentView = contentView;
    [alert show];
    _type = textField.tag;
    return NO;
}


#pragma mark - JGPickerViewDelegate -
-(void)getTimeToValue:(NSString *)theTimeStr
{
    NSString *time = [NSString stringWithFormat:@"%@:00",theTimeStr];
    if (_type == 100) {
        
        _startTime.text = time;
    }
    if (_type == 200) {
        _endTime.text = time;
    }
    
    if (![_startTime.text isEqualToString:@""] &&![_endTime.text isEqualToString:@""]) {
        
        if ( [self initTimerCompareWithStartTime:_startTime.text EndTime:_endTime.text] == 1) {
            
             [self requestDataWithStartTime:_startTime.text EndTime:_endTime.text];
        }
       
    }
    
}

- (void)button1 {
    
    self.annotation.coordinate = coords1[0];
    MAAnimatedAnnotation *anno = self.annotation;
    CLLocationCoordinate2D coords[1];
    __weak __typeof(anno) WeakAnno = anno;
//    NSDictionary *dict= self.dataArr[0];
    anno.title = @"100m/s";
    for (int i = 1; i < self.dataArr.count; i++) {
        NSDictionary *dict= self.dataArr[i];
        coords[0].latitude = [dict[@"lat"] doubleValue];
        coords[0].longitude = [dict[@"lng"] doubleValue];
        [anno addMoveAnimationWithKeyCoordinates:coords count:sizeof(coords) / sizeof(coords[0]) withDuration:0.01 withName:nil completeCallback:^(BOOL isFinished) {
//            WeakAnno.title = @"10m/s";
        }];
    }
}

- (void)button2 {
    for(MAAnnotationMoveAnimation *animation in [self.annotation allMoveAnimations]) {
        [animation cancel];
    }
    
    self.annotation.movingDirection = 0;
    self.annotation.coordinate = coords1[0];
}
#pragma mark - <MAMapViewDelegate>
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.lineWidth    = 8.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];//设置绘制直线的背景
        return polylineRenderer;
        
        
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        NSString *pointReuseIndetifier = @"myReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:pointReuseIndetifier];
            
            UIImage *imge  =  [UIImage imageNamed:@"userPosition"];
            annotationView.image =  imge;
        }
        
        annotationView.canShowCallout               = NO;
        annotationView.animatesDrop                 = NO;
        annotationView.draggable                    = NO;
        annotationView.rightCalloutAccessoryView    = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pop"]];
        
        [annotationView setSelected:YES animated:NO];
        return annotationView;
    }
    
    return nil;
}

#pragma mark 比较时间大小
-(NSInteger )initTimerCompareWithStartTime:(NSString *)start EndTime:(NSString *)end
{
    
    NSString *starTimer= start;
    NSString *finishTimer= end;
    
    BOOL result = [starTimer compare:finishTimer] == NSOrderedSame;
    NSLog(@"result:%d",result);
    if (result==1) {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"开始时间和结束时间相等" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        return 0;
    }
    
    BOOL result1 = [starTimer compare:finishTimer]==NSOrderedDescending;
    NSLog(@"result1:%d",result1);
    if (result1==1) {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"开始时间晚于结束时间" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        return -1;
    }
    
    
    BOOL result2 = [starTimer compare:finishTimer]==NSOrderedAscending;
    NSLog(@"result2:%d",result1);
    if (result2==1) {
        
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"开始时间早于结束时间" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
//        [alert show];

        return 1;
    }
    return 2;
    
}
ARRAY_INIT(dataArr);
@end
